package com.ly.heart.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ly.common.annotation.DataScope;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.SysDept;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.CommonUtil;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.*;
import com.ly.heart.domain.dto.CustomerAllocDto;
import com.ly.heart.domain.dto.CustomerDto;
import com.ly.heart.domain.dto.CustomerQueryDto;
import com.ly.heart.domain.dto.StartProcessDto;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.heart.domain.vo.CustomerVo;
import com.ly.heart.service.*;
import com.ly.heart.util.ChineseToPinyin;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.system.service.ISysDeptService;
import org.springframework.stereotype.Service;
import com.ly.heart.mapper.CustomerMapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

import static com.ly.common.utils.SecurityUtils.getLoginUser;

/**
 * 客户Service业务层处理
 *
 * @author cxl
 * @date 2024-05-14
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, CustomerEntity> implements ICustomerService {

    @Resource
    private CustomerMapper customerEntityMapper;
    @Resource
    private IBankInfoService bankInfoService;
    @Resource
    private IContactsInfoService contactsInfoService;
    @Resource
    private ICustomerUserService customerUserService;
    @Resource
    private IErpBusinessInformationService businessInformationService;
    @Resource
    private IFileInfoService fileInfoService;
    @Resource
    private IErpAddressService addressService;
    @Resource
    private IActModelService actModelService;
    @Resource
    private IActTaskCommentService actTaskCommentService;
    @Resource
    private ISysDeptService sysDeptService;
    @Resource
    private IAreaService areaService;
    @Resource
    private IActModelService iActModelService;
    @Resource
    private IKingInventoryService iKingInventoryService;
    @Resource
    private ICustomerVisitRecordService iCustomerVisitRecordService;


    /**
     * 查询客户
     *
     * @param id 客户主键
     * @return 客户
     */
    @Override
    public CustomerEntity selectCustomerEntityById ( String id ) {
        // 查询客户信息
        CustomerEntity customerEntity = customerEntityMapper.selectCustomerEntityById ( id );
        if ( customerEntity == null ) {
            return null; // 如果客户信息不存在，直接返回 null 或者抛出异常
        }
        if ( StringUtils.isNotEmpty ( customerEntity.getProvincesId () ) ) {
            AreaEntity ProvincesAreaEntity = areaService.getById ( customerEntity.getProvincesId () );
            customerEntity.setProvincesName ( ProvincesAreaEntity.getAreaName () );
            if ( StringUtils.isNotEmpty ( customerEntity.getCityId () ) ) {
                AreaEntity cityAreaEntity = areaService.getById ( customerEntity.getCityId () );
                customerEntity.setCityName ( cityAreaEntity.getAreaName () );
                if ( StringUtils.isNotEmpty ( customerEntity.getCountyId () ) ) {
                    AreaEntity areaAreaEntity = areaService.getById ( customerEntity.getCountyId () );
                    customerEntity.setCountyName ( areaAreaEntity.getAreaName () );
                }
            }
        }
        //客户更多联系人
        LambdaQueryWrapper<ContactsEntity> contactsWrapper = new LambdaQueryWrapper<> ();
        contactsWrapper.eq ( ContactsEntity :: getCustomerId, customerEntity.getId () );
        List<ContactsEntity> list = contactsInfoService.list ( contactsWrapper );
        customerEntity.setContactsEntities ( list );

        //银行信息
        LambdaQueryWrapper<BankEntity> bankWrapper = new LambdaQueryWrapper<> ();
        bankWrapper.eq ( BankEntity :: getRelationId, customerEntity.getId () );
        List<BankEntity> bankEntities = bankInfoService.list ( bankWrapper );
        customerEntity.setBankEntities ( bankEntities );

        //地址信息
        LambdaQueryWrapper<ErpAddress> addressWrapper = new LambdaQueryWrapper<> ();
        addressWrapper.eq ( ErpAddress :: getRelationId, customerEntity.getId () );
        List<ErpAddress> erpAddresses = addressService.list ( addressWrapper );
        customerEntity.setAddressEntities ( erpAddresses );

        LambdaQueryWrapper<ErpBusinessInformation> businessWrapper = new LambdaQueryWrapper<> ();
        businessWrapper.eq ( ErpBusinessInformation :: getCustomerId, customerEntity.getId () );
        ErpBusinessInformation businessInformation = businessInformationService.getOne ( businessWrapper );
        customerEntity.setBusinessInformationEntities ( businessInformation );
        return customerEntity;
    }


    /**
     * 查询客户列表
     *
     * @param customerQueryDto 客户
     * @return 客户
     */
    @Override
    @DataScope ( deptAlias = "sd" )
    public IPage<CustomerVo> selectCustomerEntityList ( CustomerQueryDto customerQueryDto ) {
        IPage<CustomerVo> customerVoIPage = customerEntityMapper.selectCustomerEntityList ( customerQueryDto );
        customerVoIPage.getRecords ().forEach ( s -> {
            ActTaskCommentEntity actTaskCommentEntity = actTaskCommentService.queryLastComment ( s.getInstanceId () );
            if ( actTaskCommentEntity != null ) {
                s.setApprovedUser ( actTaskCommentEntity.getApprovedUser () );
                s.setApprovedRemark ( actTaskCommentEntity.getRemark () );
            }
            //最后销售日期，取最后一个销售出库单的日期
            KingInventoryEntity one = iKingInventoryService.getOne ( new QueryWrapper<KingInventoryEntity> ().
                    eq ( "customer_id", s.getId () ).
                    orderByDesc ( "inventory_time" ).
                    last ( "LIMIT 1" ) );
            if ( one != null ) {
                s.setLatestSaleTime ( one.getInventoryTime () );
                //最后销售距今天的天数
                s.setLatestSaleToDays ( String.valueOf ( CommonUtil.timeDifferenceDay ( one.getInventoryTime (), new Date () ) ) );
            }
            //最后拜访日期
            CustomerVisitRecordEntity customerVisitRecordEntity = iCustomerVisitRecordService.getOne ( new QueryWrapper<CustomerVisitRecordEntity> ().
                    eq ( "customer_id", s.getId () ).
                    orderByDesc ( "visit_time" ).
                    last ( "LIMIT 1" ) );
            if ( customerVisitRecordEntity != null ) {
                s.setLatestVisitTime ( customerVisitRecordEntity.getVisitTime () );
                //最后拜访距今天的天数
                s.setLatestVisitToDays ( String.valueOf ( CommonUtil.timeDifferenceDay ( customerVisitRecordEntity.getVisitTime (), new Date () ) ) );
            }
            //任务信息
            ActCurrentTaskVo currentTaskVo = iActModelService.getCurrentTaskByInstanceId ( s.getInstanceId () );
            Optional.ofNullable ( currentTaskVo ).ifPresent ( currentTask -> {
                s.setCurrentTask ( currentTask );
            } );
        } );
        return customerVoIPage;
    }


    /**
     * 新增客户
     * 客户基础表erp_customer_info，需上传附件可支撑多个附件
     * * 新增客户时需要同时新增erp_customer_user_info用户、客户关联关系数据
     * * 客户更多联系人数据erp_contacts_info多个
     *
     * @param customerDto 客户
     * @return 结果
     */
    @Override
    @Transactional ( propagation = Propagation.REQUIRED, rollbackFor = {Exception.class} )
    public AjaxResult draft ( CustomerDto customerDto ) {
        // 使用局部变量减少DateUtils.getNowDate()的多次调用
        Date nowDate = DateUtils.getNowDate ();
        String customerId = SnowflakeIdWorker.getInstance ().nextStringId ();
        customerDto.getCustomerEntity ().setId ( customerId );
        customerDto.getCustomerEntity ().setCreateTime ( nowDate );
        customerDto.getCustomerEntity ().setCreateId ( String.valueOf ( getLoginUser ().getUser ().getUserId () ) );
        String companyId = CurrentUserUtil.getCompanyId ();
        SysDept sysDept = sysDeptService.getById ( companyId );
        int count = this.count ();
        String countStr = String.format ( "%06d", count );
        String firstLetter = ChineseToPinyin.getFirstLetter ( sysDept.getDeptName () );
        String customerCode = firstLetter.concat ( "_KHBM_" ).concat ( countStr );
        customerDto.getCustomerEntity ().setCustomerCode ( customerCode );
        //StartProcessDto startDto = new StartProcessDto ();
        //if ( customerDto.getCustomerEntity ().getType ().equals ( ConstUtil.CUSTOMER_BUSINESS_MANAGER ) ) {
        //    startDto.setBusinessId ( customerId ).setBusinessType ( customerDto.getCustomerEntity ().getBusinessType () ).setModelId ( customerDto.getCustomerEntity ().getModelId () )
        //            .setBusinessName ( "商机管理_".concat ( customerId ) );
        //} else {
        //    startDto.setBusinessId ( customerId ).setBusinessType ( customerDto.getCustomerEntity ().getBusinessType () ).setModelId ( customerDto.getCustomerEntity ().getModelId () )
        //            .setBusinessName ( "客户管理_".concat ( customerId ) );
        //}
        //String instanceId = actModelService.startProcess ( startDto );
        //customerDto.getCustomerEntity ().setInstanceId ( instanceId );
        customerDto.getCustomerEntity ().setState ( ConstUtil.STATE_IN_DRAFT );
        boolean saved = this.save ( customerDto.getCustomerEntity () );
        if ( ! saved ) {
            // 处理插入失败逻辑，例如设置错误信息或抛出自定义异常
            throw new RuntimeException ( "插入客户实体失败" );
        }
        // 银行信息处理
        if ( ! CollectionUtils.isEmpty ( customerDto.getBankEntities () ) ) {
            Integer bankType = ConstUtil.BANK_TYPE_CUSTOMER;
            customerDto.getBankEntities ().forEach ( bankEntity -> {
                bankEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                bankEntity.setRelationId ( customerId );
                bankEntity.setCreateTime ( nowDate );
                bankEntity.setType ( bankType );
                bankEntity.setCreateBy ( String.valueOf ( getLoginUser ().getUser ().getUserId () ) );
            } );
            boolean isBank = bankInfoService.saveBatch ( customerDto.getBankEntities () );
            if ( ! isBank ) {
                // 处理插入失败逻辑
                throw new RuntimeException ( "插入银行信息失败" );
            }
        }

        // 联系人信息处理
        if ( ! CollectionUtils.isEmpty ( customerDto.getContactsEntities () ) ) {
            List<ContactsEntity> contactsEntities = customerDto.getContactsEntities ();
            contactsEntities.forEach ( contactsEntity -> {
                contactsEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                contactsEntity.setCustomerId ( customerId );
                contactsEntity.setCreateTime ( nowDate );
                contactsEntity.setCreateBy ( String.valueOf ( getLoginUser ().getUser ().getUserId () ) );
            } );
            boolean saveBatchResult = contactsInfoService.saveBatch ( contactsEntities );
            if ( ! saveBatchResult ) {
                // 处理保存失败逻辑
                throw new RuntimeException ( "保存联系人信息失败" );
            }
        }

        //商务信息处理
        if ( ObjectUtil.isNotEmpty ( customerDto.getErpBusinessInformation () ) ) {
            customerDto.getErpBusinessInformation ().setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
            customerDto.getErpBusinessInformation ().setCustomerId ( customerId );
            customerDto.getErpBusinessInformation ().setCreateTime ( nowDate );
            customerDto.getErpBusinessInformation ().setCreateBy ( String.valueOf ( getLoginUser ().getUser ().getUserId () ) );
            boolean save = businessInformationService.save ( customerDto.getErpBusinessInformation () );
            if ( ! save ) {
                throw new RuntimeException ( "新增商务信息失败" );
            }
        }

        //地址信息处理
        if ( ! CollectionUtils.isEmpty ( customerDto.getAddresses () ) ) {
            customerDto.getAddresses ().forEach ( address -> {
                address.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                address.setRelationId ( customerId );
                address.setCreateTime ( nowDate );
                address.setCreateBy ( String.valueOf ( getLoginUser ().getUser ().getUserId () ) );
            } );
            boolean saveBatch = addressService.saveBatch ( customerDto.getAddresses () );
            if ( ! saveBatch ) {
                throw new RuntimeException ( "新增地址信息失败" );
            }
        }

        //添加用户、客户关联关系；当提供商机/客户重复时，则可以共享同一个客户
        CustomerUserEntity customerUserEntity = new CustomerUserEntity ();
        customerUserEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        customerUserEntity.setCustomerId ( customerId );
        customerUserEntity.setCreateTime ( nowDate );
        customerUserEntity.setUserId ( String.valueOf ( getLoginUser ().getUser ().getUserId () ) );
        boolean save = customerUserService.save ( customerUserEntity );
        if ( ! save ) {
            throw new RuntimeException ( "新增客户失败" );
        }
        //修改附件
        if ( ! CollectionUtils.isEmpty ( customerDto.getCustomerEntity ().getFileIds () ) ) {
            List<FileEntity> fileEntities = new ArrayList<> ();
            customerDto.getCustomerEntity ().getFileIds ().forEach ( fileId -> {
                FileEntity fileEntity = new FileEntity ();
                fileEntity.setRelationId ( customerId );
                fileEntity.setId ( fileId );
                fileEntity.setCreateTime ( nowDate );
            } );
            boolean b = fileInfoService.updateBatchById ( fileEntities );
            if ( ! b ) {
                throw new RuntimeException ( "新增客户失败" );
            }
        }
        return AjaxResult.success ( "暂存客户成功", customerId );
    }

    /**
     * 提交客户信息
     *
     * @param customerEntity
     * @return
     */
    @Transactional ( propagation = Propagation.REQUIRED, rollbackFor = {Exception.class} )
    public AjaxResult submit ( CustomerEntity customerEntity ) {
        if ( StringUtils.isBlank ( customerEntity.getId () ) ) {
            return AjaxResult.error ( "请先暂存该单据！" );
        }
        CustomerEntity customer = this.getById ( customerEntity );
        StartProcessDto startDto = new StartProcessDto ();
        if ( customer.getType ().equals ( ConstUtil.CUSTOMER_BUSINESS_MANAGER ) ) {
            startDto.setBusinessId ( customer.getId () ).setBusinessType ( customerEntity.getBusinessType () ).setModelId ( customerEntity.getModelId () )
                    .setBusinessName ( "商机管理_".concat ( customer.getId () ) );
        } else {
            startDto.setBusinessId ( customer.getId () ).setBusinessType ( customerEntity.getBusinessType () ).setModelId ( customerEntity.getModelId () )
                    .setBusinessName ( "客户管理_".concat ( customer.getId () ) );
        }
        String instanceId = actModelService.startProcess ( startDto );
        //联表做相应的操作
        CustomerDto customerDto = new CustomerDto ();
        customerDto.setContactsEntities ( customerEntity.getContactsEntities () );
        customerDto.setBankEntities ( customerEntity.getBankEntities () );
        customerDto.setAddresses ( customerEntity.getAddressEntities () );
        updateContactsEntities ( customerDto );
        if ( ! Objects.isNull ( customerEntity.getBusinessInformationEntities () ) ) {
            boolean b = businessInformationService.updateById ( customerEntity.getBusinessInformationEntities () );
            if ( ! b ) {
                return AjaxResult.error ( "修改客户实体失败" );
            }
        }
        boolean update = this.update ( new LambdaUpdateWrapper<CustomerEntity> ().set ( CustomerEntity :: getInstanceId, instanceId ).set ( CustomerEntity :: getState, ConstUtil.STATE_IN_PROCESS ).eq ( CustomerEntity :: getId, customerEntity.getId () ) );
        if ( ! update ) {
            throw new CustomException ( "提交" + ( customer.getType ().equals ( ConstUtil.CUSTOMER_BUSINESS_MANAGER ) ? "商机" : "客户" + "失败" ) );
        }
        return AjaxResult.success ( "提交" + ( customer.getType ().equals ( ConstUtil.CUSTOMER_BUSINESS_MANAGER ) ? "商机" : "客户" + "成功" ) );
    }

    /**
     * 修改客户
     *
     * @param customerDto 客户
     * @return 结果
     */
    @Override
    @Transactional ( propagation = Propagation.REQUIRED, rollbackFor = {Exception.class} )
    public AjaxResult updateCustomerEntity ( CustomerDto customerDto ) {
        boolean updated = this.updateById ( customerDto.getCustomerEntity () );
        if ( ! updated ) {
            return AjaxResult.error ( "修改客户实体失败" );
        }
        updateContactsEntities ( customerDto );
        if ( ObjectUtil.isNotEmpty ( customerDto.getErpBusinessInformation () ) ) {
            boolean b = businessInformationService.updateById ( customerDto.getErpBusinessInformation () );
            if ( ! b ) {
                return AjaxResult.error ( "修改客户实体失败" );
            }
        }
        return AjaxResult.success ();
    }

    /**
     * 修改客户基本信息
     *
     * @param customerEntity
     * @return
     */
    @Override
    public AjaxResult updateSingle ( CustomerEntity customerEntity ) {
        LambdaUpdateWrapper<CustomerEntity> updateWrapper = new LambdaUpdateWrapper ();
        if ( customerEntity.getType () != null ) {
            updateWrapper.set ( CustomerEntity :: getType, customerEntity.getType () );
        }
        boolean update = this.update ( updateWrapper.eq ( CustomerEntity :: getId, customerEntity.getId () ) );
        if ( ! update ) {
            throw new CustomException ( "修改客户基本信息失败！" );
        }
        return AjaxResult.success ( "修改客户基本信息成功" );
    }

    /**
     * 批量删除客户
     *
     * @param ids 需要删除的客户主键
     * @return 结果
     */
    @Override
    public int deleteCustomerEntityByIds ( String[] ids ) {
        return customerEntityMapper.deleteCustomerEntityByIds ( ids );
    }

    /**
     * 分盘所选客户给指定客户
     *
     * @param customerAllocDto
     * @return
     */
    @Override
    public AjaxResult alloc ( CustomerAllocDto customerAllocDto ) {
        List<CustomerEntity> customerEntities = customerAllocDto.getCustomerEntities ();
        List<String> ids = customerEntities.stream ().map ( CustomerEntity :: getId ).collect ( Collectors.toList () );
        customerUserService.remove ( new LambdaUpdateWrapper<CustomerUserEntity> ().in ( CustomerUserEntity :: getCustomerId, ids ) );
        customerEntities.forEach ( customerEntity -> {
            CustomerUserEntity customerUserEntity = new CustomerUserEntity ();
            customerUserEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
            customerUserEntity.setCustomerId ( customerEntity.getId () );
            customerUserEntity.setCreateTime ( DateUtils.getNowDate () );
            customerUserEntity.setUserId ( customerAllocDto.getSysUser ().getUserId () );
            boolean save = customerUserService.save ( customerUserEntity );
            if ( ! save ) {
                throw new CustomException ( "分配失败！" );
            }
        } );
        return AjaxResult.success ();
    }

    /**
     * 删除客户信息
     *
     * @param id 客户主键
     * @return 结果
     */
    @Override
    public int deleteCustomerEntityById ( String id ) {
        return customerEntityMapper.deleteCustomerEntityById ( id );
    }

    /**
     * 禁用客户
     *
     * @param id
     * @return
     */
    @Override
    public AjaxResult disabled ( String id ) {
        CustomerEntity customerEntity = this.getById ( id );
        if ( customerEntity.getState ().equals ( ConstUtil.STATE_IN_PROCESS ) ) {
            return AjaxResult.error ( "该客户正在审批中，不能禁用" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<CustomerEntity> ()
                .set ( CustomerEntity :: getIsDisabled, customerEntity.equals ( "1" ) ? "2" : "1" )
                .eq ( CustomerEntity :: getId, id )
        );
        if ( ! update ) {
            String message = customerEntity.getIsDisabled ().equals ( "1" ) ? "禁用失败" : "解禁失败";
            return AjaxResult.error ( message );
        }
        String successMessage = customerEntity.getIsDisabled ().equals ( "1" ) ? "禁用成功" : "解禁成功";
        return AjaxResult.success ( successMessage );
    }

    //修改联系人信息
    private void updateContactsEntities ( CustomerDto customerDto ) {
        if ( ! CollectionUtils.isEmpty ( customerDto.getContactsEntities () ) ) {
            // 分别处理新增、更新和删除逻辑
            handleAdd ( customerDto, "contacts" );
            handleUpdate ( customerDto, "contacts" );
            handleDelete ( customerDto, "contacts" );
        }
        if ( ! CollectionUtils.isEmpty ( customerDto.getBankEntities () ) ) {
            // 分别处理新增、更新和删除逻辑
            handleAdd ( customerDto, "bank" );
            handleUpdate ( customerDto, "bank" );
            handleDelete ( customerDto, "bank" );
        }

        if ( ! CollectionUtils.isEmpty ( customerDto.getAddresses () ) ) {
            handleAdd ( customerDto, "address" );
            handleUpdate ( customerDto, "address" );
            handleDelete ( customerDto, "address" );
        }

    }

    private void handleAdd ( CustomerDto customerDto, String type ) {
        if ( "contacts".equals ( type ) ) {
            List<ContactsEntity> addContactEntities = customerDto.getContactsEntities ().stream ()
                    .filter ( s -> StringUtils.isEmpty ( s.getId () ) ).collect ( Collectors.toList () );
            if ( ! CollectionUtils.isEmpty ( addContactEntities ) ) {
                boolean b = contactsInfoService.saveBatch ( addContactEntities );
                if ( ! b ) {
                    throw new RuntimeException ( "修改联系人信息失败 - 新增" );
                }
            }
        }
        if ( "bank".equals ( type ) ) {
            List<BankEntity> addBankEntities = customerDto.getBankEntities ().stream ()
                    .filter ( s -> StringUtils.isEmpty ( s.getId () ) ).collect ( Collectors.toList () );
            if ( ! CollectionUtils.isEmpty ( addBankEntities ) ) {
                boolean b = bankInfoService.saveBatch ( addBankEntities );
                if ( ! b ) {
                    throw new RuntimeException ( "修改银行信息失败 - 新增" );
                }
            }
        }
        if ( "address".equals ( type ) ) {
            List<ErpAddress> updateAddressEntities = customerDto.getAddresses ().stream ()
                    .filter ( s -> StringUtils.isNotEmpty ( s.getId () ) ).collect ( Collectors.toList () );
            if ( ! CollectionUtils.isEmpty ( updateAddressEntities ) ) {
                boolean b = addressService.updateBatchById ( updateAddressEntities );
                if ( ! b ) {
                    throw new RuntimeException ( "修改地址信息失败- 新增" );
                }
            }
        }

    }

    private void handleUpdate ( CustomerDto customerDto, String type ) {
        if ( "contacts".equals ( type ) ) {
            List<ContactsEntity> updateContactsEntities = customerDto.getContactsEntities ().stream ()
                    .filter ( s -> StringUtils.isNotEmpty ( s.getId () ) ).collect ( Collectors.toList () );
            if ( ! CollectionUtils.isEmpty ( updateContactsEntities ) ) {
                boolean b = contactsInfoService.updateBatchById ( updateContactsEntities );
                if ( ! b ) {
                    throw new RuntimeException ( "修改联系人信息失败 - 更新" );
                }
            }
        }
        if ( "bank".equals ( type ) ) {
            List<BankEntity> updateBankEntities = customerDto.getBankEntities ().stream ()
                    .filter ( s -> StringUtils.isNotEmpty ( s.getId () ) ).collect ( Collectors.toList () );
            if ( ! CollectionUtils.isEmpty ( updateBankEntities ) ) {
                boolean b = bankInfoService.updateBatchById ( updateBankEntities );
                if ( ! b ) {
                    throw new RuntimeException ( "修改银行信息失败 - 更新" );
                }
            }
        }
        if ( "address".equals ( type ) ) {
            List<ErpAddress> updateAddressEntities = customerDto.getAddresses ().stream ()
                    .filter ( s -> StringUtils.isNotEmpty ( s.getId () ) ).collect ( Collectors.toList () );
            if ( ! CollectionUtils.isEmpty ( updateAddressEntities ) ) {
                boolean b = addressService.updateBatchById ( updateAddressEntities );
                if ( ! b ) {
                    throw new RuntimeException ( "修改地址信息失败 - 更新" );
                }
            }
        }

    }

    private void handleDelete ( CustomerDto customerDto, String type ) {
        if ( "contacts".equals ( type ) ) {
            List<ContactsEntity> list = contactsInfoService.list ( new LambdaQueryWrapper<ContactsEntity> ()
                    .eq ( ContactsEntity :: getCustomerId, customerDto.getCustomerEntity ().getId () ) );

            List<ContactsEntity> deleteContactsEntities = list.stream ()
                    .filter ( s -> ! customerDto.getContactsEntities ().stream ().anyMatch ( t -> t.getId ().equals ( s.getId () ) ) )
                    .collect ( Collectors.toList () );

            if ( ! CollectionUtils.isEmpty ( deleteContactsEntities ) ) {
                boolean remove = contactsInfoService.removeByIds ( deleteContactsEntities.stream ()
                        .map ( ContactsEntity :: getId ).collect ( Collectors.toList () ) );
                if ( ! remove ) {
                    throw new RuntimeException ( "修改联系人信息失败 - 删除" );
                }
            }
        }
        if ( "bank".equals ( type ) ) {
            List<BankEntity> list = bankInfoService.list ( new LambdaQueryWrapper<BankEntity> ()
                    .eq ( BankEntity :: getRelationId, customerDto.getCustomerEntity ().getId () ) );

            List<BankEntity> deleteBankEntities = list.stream ()
                    .filter ( s -> ! customerDto.getBankEntities ().stream ().anyMatch ( t -> t.getId ().equals ( s.getId () ) ) )
                    .collect ( Collectors.toList () );

            if ( ! CollectionUtils.isEmpty ( deleteBankEntities ) ) {
                boolean remove = contactsInfoService.removeByIds ( deleteBankEntities.stream ()
                        .map ( BankEntity :: getId ).collect ( Collectors.toList () ) );
                if ( ! remove ) {
                    throw new RuntimeException ( "修改银行信息失败 - 删除" );
                }
            }

        }
        if ( "address".equals ( type ) ) {
            List<ErpAddress> list = addressService.list ( new LambdaQueryWrapper<ErpAddress> ()
                    .eq ( ErpAddress :: getRelationId, customerDto.getCustomerEntity ().getId () ) );

            List<ErpAddress> deleteAddressEntities = list.stream ()
                    .filter ( s -> ! customerDto.getAddresses ().stream ().anyMatch ( t -> t.getId ().equals ( s.getId () ) ) )
                    .collect ( Collectors.toList () );

            if ( ! CollectionUtils.isEmpty ( deleteAddressEntities ) ) {
                boolean remove = contactsInfoService.removeByIds ( deleteAddressEntities.stream ()
                        .map ( ErpAddress :: getId ).collect ( Collectors.toList () ) );
                if ( ! remove ) {
                    throw new RuntimeException ( "修改地址信息失败 - 删除" );
                }
            }
        }


    }


}
